package main.controller;

import java.util.List;

import main.entity.ReplyVO;
import main.entity.ThreadsVO;
import main.service.ChannelService;
import main.service.ThreadsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/threads")
public class ThreadsCtrl extends BaseCtrl<ThreadsVO> {

	@Autowired
	private ThreadsService thService;
	@Autowired
	private ChannelService channelService;
	@Autowired
	private ReplyCtrl replyCtrl;
	
	private String targetURL;
	
	private ThreadsCtrl() {
		this.targetURL = "error";//default is error page
	}

	
	@RequestMapping(value="/pub.do")
	public void pubThreads(@ModelAttribute ThreadsVO threadsVO){
		Integer threadsID = thService.save(threadsVO);	
		if (threadsID!=null) {
			threadsDetails(new Integer(threadsID));
		}
	}
	
	@RequestMapping(value="/{threadsID}/read.do")
	public ModelAndView threadsDetails(@PathVariable("threadsID") Integer threadsID){
		ThreadsVO threadsVO = thService.getByID(ThreadsVO.class, threadsID);
		List<ReplyVO> replysByThreads = replyCtrl.getByThreadsID(threadsID);
		ModelAndView mdv = new ModelAndView();
		mdv.addObject("threads", threadsVO);
		mdv.addObject("replys", replysByThreads);
//		request.setAttribute("threads", threadsVO);
//		request.setAttribute("replysByThreads", replysByThreads);
//		targetURL="/threads/"+threadsID;
		mdv.setViewName("/threadsDetails");
		return mdv;
	}
	
	@RequestMapping(value="/update.do")
	public void updThreads(@ModelAttribute ThreadsVO threads){
		Boolean isOK = thService.update(threads);
		Integer threadsID= threads.getThreadsID();
		if (isOK) {
//			request.setAttribute("threads", threadsVO);
			threadsDetails(threadsID);// ?????????????
		}
//		return targetURL;
	}
	
	@RequestMapping(value="/{threadsID}/delete.do")
	public String delThreads(@PathVariable("threadsID") Integer threadsID){
		if(thService.remove(threadsID)){
			targetURL = "/module/3";
		}
		return targetURL;
	}
	
	@RequestMapping(value="/readHotThreads.do", method=RequestMethod.POST)
	@ResponseBody
	public List<ThreadsVO> readHotThreads(){
		List<ThreadsVO> hotThreads = thService.readHoThreads();
		return hotThreads;
	}
	
}
